interface options {
  /**
   * 文件大小提示
   */
  tip?: boolean;
  name?: string | undefined;
}
/**
 * 链接跨域检测
 * @param url
 * @returns
 */
const corsEnabled = (url: string | URL) => {
  var xhr = new XMLHttpRequest();
  xhr.open("HEAD", url, false);
  try {
    xhr.send();
  } catch (e) {}
  return xhr.status >= 200 && xhr.status <= 299;
};
/**
 * 请求资源
 * @param url
 * @param name
 */
const downLoad = (
  url: string,
  options: options = {
    name: "download",
  }
) => {
  let xhr = new XMLHttpRequest();

  xhr.open("GET", url);
  xhr.responseType = "blob";
  xhr.onload = function () {
    FileSaver(xhr.response, options);
  };

  xhr.send();
};
const click = (node: HTMLAnchorElement) => {
  node.target = "_blank";
  node.click();
  setTimeout(() => {
    node.remove();
  }, 0);
};
/**
 * blob流处理方式
 */
const deelBlob = (url: Blob, options: options) => {
  const a = document.createElement("a");
  a.rel = "noopener";
  a.href = URL.createObjectURL(url);
  a.download = options.name!;
  click(a);
};
const deelUrl = (url: string, options: options) => {
  const a = document.createElement("a");
  a.rel = "noopener";
  const file = url.split("/"); //文件目录
  options.name = file[file.length - 1]; //文件名
  a.href = url; //链接赋值
  a.download = options.name;
  /**
   * 由于重定向  和本网站不同源可能被拦截
   */
  if (a.origin !== location.origin) {
    corsEnabled(a.href) ? downLoad(url, options) : click(a);
  }
};
export const FileSaver = (
  url?: string | Blob,
  options: options = {
    name: "download",
  }
) => {
  if (url) {
    if (typeof url === "string") {
      let isBlocked = false;
      try {
        let popup = window.open(url, "_blank");
        if (popup == null || typeof popup == "undefined") {
          //弹出窗口被拦截，window.open被禁用
          isBlocked = true;
        }
      } catch (error) {
        isBlocked = true;
      }
      if (isBlocked) {
        deelUrl(url, options);
      }
    } else {
      deelBlob(url, options);
    }
  } else {
    new Error("没有资源");
  }
};
